package brickdestroyer.util;

import java.awt.Image;
import java.io.File;
import java.util.Collection;
import java.util.Map;
import java.util.TreeMap;

/**
 * This class manages all images in the game.
 * <p>The idea is that this resource class can
 * load all the images initally and have them for
 * fast read when an object requires them.
 *
 * @author Momchil Atanasov
 */
public final class ImageResources {

    private static String packagePathname = "";

    private static Map<String, Image> images = new TreeMap<String, Image>();


    /**
     * Initializes the resource manager to a given
     * pathname where the game images are placed.
     * <p>Note: This pathname should hold only images.
     * @param pathname pathname to the images folder
     */
    public static void initialize(String pathname) {
        packagePathname = pathname;
        if (!pathname.endsWith("/")) {
            pathname += "/";
        }

        Collection<File> files = ResourceTool.listFilesInPackage(packagePathname);
        for (File file : files) {
            insertImage(file.getName());
        }
    }

    public static void deinitialize() {
    }

    /**
     * This method finds an image by it's name and
     * returns it. If such image does not exist in the
     * resource collection then it get's loaded from the
     * source pathname for future needs.
     * @param name name of the image file.
     * @return required image object.
     */
    public static Image getImage(String name) {
        name = name.toLowerCase();
        if (images.containsKey(name)) {
            return images.get(name);
        } else {
            System.err.println("[ImageResources] : Forcefully loading image: " + name);
            return insertImage(name);
        }
    }

    private static Image insertImage(String name) {
        Image result = ResourceTool.loadImage(packagePathname + name);
        images.put(name, result);
        return result;
    }

    private ImageResources() {
    }
}
